<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="springboot,mongo," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="1、简单配置1.1 在springboot的配置文件 (如application.properties)中配置mongo的urlspring.data.mongodb.uri=mongodb://@ip:prot/database#用户和密码配置spring.data.mongodb.uri=mongodb://user:password@ip:prot/database#多个IP集群配置spri">
<meta name="keywords" content="springboot,mongo">
<meta property="og:type" content="article">
<meta property="og:title" content="springboot 配置mongo">
<meta property="og:url" content="https://gitee.com/shuhao/2017/11/20/springboot-配置mongo/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="1、简单配置1.1 在springboot的配置文件 (如application.properties)中配置mongo的urlspring.data.mongodb.uri=mongodb://@ip:prot/database#用户和密码配置spring.data.mongodb.uri=mongodb://user:password@ip:prot/database#多个IP集群配置spri">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-11-20T11:30:16.320Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="springboot 配置mongo">
<meta name="twitter:description" content="1、简单配置1.1 在springboot的配置文件 (如application.properties)中配置mongo的urlspring.data.mongodb.uri=mongodb://@ip:prot/database#用户和密码配置spring.data.mongodb.uri=mongodb://user:password@ip:prot/database#多个IP集群配置spri">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2017/11/20/springboot-配置mongo/"/>





  <title> springboot 配置mongo | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2017/11/20/springboot-配置mongo/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                springboot 配置mongo
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-20T11:19:48+08:00">
                2017-11-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/springboot/" itemprop="url" rel="index">
                    <span itemprop="name">springboot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="1、简单配置"><a href="#1、简单配置" class="headerlink" title="1、简单配置"></a>1、简单配置</h1><h3 id="1-1-在springboot的配置文件-如application-properties-中配置mongo的url"><a href="#1-1-在springboot的配置文件-如application-properties-中配置mongo的url" class="headerlink" title="1.1 在springboot的配置文件 (如application.properties)中配置mongo的url"></a>1.1 在springboot的配置文件 (如application.properties)中配置mongo的url</h3><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">spring.data.mongodb.uri=mongodb://@ip:prot/database</span><br><span class="line"></span><br><span class="line">#用户和密码配置</span><br><span class="line">spring.data.mongodb.uri=mongodb://user:password@ip:prot/database</span><br><span class="line"></span><br><span class="line">#多个IP集群配置</span><br><span class="line">spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database</span><br></pre></td></tr></table></figure>
<h3 id="1-2-在需要使用mongo的地方引入MongoTemplate来与数据库交互"><a href="#1-2-在需要使用mongo的地方引入MongoTemplate来与数据库交互" class="headerlink" title="1.2 在需要使用mongo的地方引入MongoTemplate来与数据库交互"></a>1.2 在需要使用mongo的地方引入MongoTemplate来与数据库交互</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line">MongoTemplate mongoTemplate</span><br></pre></td></tr></table></figure>
<p><a href="http://shuhao.gitee.io/blog/2017/11/20/springboot%E5%AF%B9Mongo%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5%E7%9A%84%E6%96%B9%E5%BC%8F/" target="_blank" rel="external">关于如何如何使用mongoTemplate操作数据库</a></p>
<h1 id="2、Mongo的配置"><a href="#2、Mongo的配置" class="headerlink" title="2、Mongo的配置"></a>2、Mongo的配置</h1><h3 id="2-1-正springboot配置文件中-配置mongo的参数信息"><a href="#2-1-正springboot配置文件中-配置mongo的参数信息" class="headerlink" title="2.1 正springboot配置文件中 配置mongo的参数信息"></a>2.1 正springboot配置文件中 配置mongo的参数信息</h3><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">mongo.oss.replicaSet=172.20.176.143:27017,172.20.176.144:27017 </span><br><span class="line">mongo.dbname=linkerp</span><br><span class="line">mongo.connectionsPerHost=200</span><br><span class="line">mongo.threadsAllowedToBlockForConnectionMultiplier=10</span><br><span class="line">mongo.maxWaitTime=120000</span><br><span class="line">mongo.connectTimeout=10000</span><br><span class="line">mongo.socketTimeout=10000</span><br><span class="line">mongo.autoConnectRetry=true</span><br><span class="line"></span><br><span class="line">#mongo的读参考</span><br><span class="line">#primary模式：读操作从primary节点上进行，如果primary节点故障，则产生一个错误或返回异常</span><br><span class="line">#secondary模式：读操作从secondary节点上进行，没有可用的secondary节点则产生一个错误或返回异常</span><br><span class="line">#secondaryPreferred模式：在大多数情况下，读操作在secondary节点上进行，但当复制集中只有一个primary节点时，读操作将用这个复制集的primary节点</span><br><span class="line">#nearest模式：读操作从最近的节点上进行，有可能为primary节点，有可能为secondary节点，不考虑节点类型</span><br><span class="line">mongo.readPreference=primaryPreferred #读操作从primary节点上进行，如果primary节点故障，则读操作被路由到secondary节点</span><br><span class="line"></span><br><span class="line">#标签，针对特定标签定义特殊的谢关注模式。可设置多个</span><br><span class="line">mongo.tags.key=datacenter</span><br><span class="line">mongo.tags.value=jinshanyun</span><br></pre></td></tr></table></figure>
<h3 id="2-2-配置MongoTemplate"><a href="#2-2-配置MongoTemplate" class="headerlink" title="2.2 配置MongoTemplate"></a>2.2 配置MongoTemplate</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">#配置MongoClient</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#配置MongoDBFactory</span><br><span class="line"></span><br><span class="line">#配置MappingMongoConverter</span><br><span class="line"></span><br><span class="line">#配置MongoTemplate</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mongodb.MongoClient;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.MongoClientOptions;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.ReadPreference;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.ServerAddress;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.Tag;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.TagSet;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.lang3.StringUtils;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Value;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.MongoDbFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.MongoTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.SimpleMongoDbFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.convert.MappingMongoConverter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.mapping.MongoMappingContext;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MongoConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mongo.dbname&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String database;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mongo.oss.replicaSet&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String replicaSet;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mongo.connectionsPerHost&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> connectionPerHost;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mongo.threadsAllowedToBlockForConnectionMultiplier&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> threads;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mongo.connectTimeout&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> connectTimeout;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mongo.maxWaitTime&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> maxWaitTime;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mongo.socketTimeout&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> socketTimeout;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mongo.tags.key&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String tagKey;</span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;mongo.tags.value&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String tagValue;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 配置MongoClient参数</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> MongoClientOptions <span class="title">mongoClientOptions</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> MongoClientOptions.builder().connectionsPerHost(connectionPerHost).threadsAllowedToBlockForConnectionMultiplier(threads)</span><br><span class="line">                .connectTimeout(connectTimeout).maxWaitTime(maxWaitTime).socketTimeout(socketTimeout).build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据逗号分隔复制集的地址生产ServerAddress列表</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> List&lt;ServerAddress&gt; <span class="title">parseReplicaSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (StringUtils.isBlank(replicaSet)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"mongodb replicaset配置格式错误:"</span> + replicaSet);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        String[] replicas = replicaSet.trim().split(<span class="string">","</span>);</span><br><span class="line">        List&lt;ServerAddress&gt; serverAddressList = <span class="keyword">new</span> ArrayList&lt;&gt;(replicas.length);</span><br><span class="line">        <span class="keyword">for</span> (String replica : replicas) &#123;</span><br><span class="line">            String[] hostAndPort = replica.split(<span class="string">":"</span>);</span><br><span class="line">            serverAddressList.add(<span class="keyword">new</span> ServerAddress(hostAndPort[<span class="number">0</span>], Integer.parseInt(hostAndPort[<span class="number">1</span>])));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> serverAddressList;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 生产MongoClient</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MongoClient <span class="title">mongoClient</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;ServerAddress&gt; serverAddresses = parseReplicaSet();</span><br><span class="line">        MongoClientOptions options = mongoClientOptions();</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MongoClient(serverAddresses, options);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 生产MongoDBFactory</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MongoDbFactory <span class="title">mongoDbFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> SimpleMongoDbFactory(mongoClient(), database);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MongoMappingContext <span class="title">mappingContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MongoMappingContext();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * MappingMongoConverter</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MappingMongoConverter <span class="title">mappingMongoConverter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 以下1行代码用于避免mongotemplate将符合ObjectId格式的字符串主键转换为ObjectId对象来存储</span></span><br><span class="line">        <span class="comment">// MappingMongoConverter mappingMongoConverter = new</span></span><br><span class="line">        <span class="comment">// CloudFormMappingMongoConverter(new</span></span><br><span class="line">        <span class="comment">// DefaultDbRefResolver(mongoDbFactory), mappingContext);</span></span><br><span class="line">        MappingMongoConverter mappingMongoConverter = <span class="keyword">new</span> MappingMongoConverter(<span class="keyword">new</span> DefaultDbRefResolver(mongoDbFactory()), mappingContext());</span><br><span class="line">        <span class="keyword">return</span> mappingMongoConverter;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DefaultMongoTypeMapper <span class="title">defaultMongoTypeMapper</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DefaultMongoTypeMapper();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 调用mongoTemplate的save方法时, spring-data-mongodb的TypeConverter会自动给document添加一个_class属性, 值是你保存的类名.</span></span><br><span class="line"><span class="comment">     * 这种设计并没有什么坏处. spring-data-mongodb是为了在把document转换成Java对象时能够转换到具体的子类. 但有时候我们并不希望出现这个字段,</span></span><br><span class="line"><span class="comment">     * 主要是看上去会比较"烦". 可以通过设置MappingMongoConverter的MongoTypeMapper来解决这个问题.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MongoTemplate <span class="title">mongoTemplate</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        MappingMongoConverter mappingMongoConverter = mappingMongoConverter();</span><br><span class="line">        mappingMongoConverter.setTypeMapper(<span class="keyword">new</span> DefaultMongoTypeMapper(<span class="keyword">null</span>));</span><br><span class="line">        MongoTemplate mongoTemplate = <span class="keyword">new</span> MongoTemplate(mongoDbFactory(), mappingMongoConverter);</span><br><span class="line">        mongoTemplate.setReadPreference(secondaryPreferredReadPreference(tagSetObject(tagObject())));</span><br><span class="line">        <span class="keyword">return</span> mongoTemplate;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> Tag <span class="title">tagObject</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Tag(tagKey, tagValue);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 复制集</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> tag</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TagSet <span class="title">tagSetObject</span><span class="params">(Tag tag)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TagSet(tag);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 优先从secondary节点进行读取操作，secondary节点不可用时从主节点读取数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> tagSet</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ReadPreference <span class="title">secondaryPreferredReadPreference</span><span class="params">(TagSet tagSet)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> ReadPreference.secondaryPreferred(tagSet);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><em>总结MongoTemplate的配置分为：MongoClient、MongoDBFactory、MappingMongoConverter、MongoTemplate</em></p>
<h3 id="2-3-使用MongoTemplate"><a href="#2-3-使用MongoTemplate" class="headerlink" title="2.3 使用MongoTemplate"></a>2.3 使用MongoTemplate</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line">MongoTemplate mongoTemplate;</span><br></pre></td></tr></table></figure>
<h1 id="3-多数据源配置"><a href="#3-多数据源配置" class="headerlink" title="3 多数据源配置"></a>3 多数据源配置</h1><p>参考<a href="http://www.ityouknow.com/springboot/2017/05/08/springboot-mongodb.html" target="_blank" rel="external">使用spring-boot-autoconfigure配置多Mongo数据源</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/springboot/" rel="tag"># springboot</a>
          
            <a href="/blog/tags/mongo/" rel="tag"># mongo</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2017/11/15/本地仓库连接git远程仓库/" rel="next" title="本地仓库连接git远程仓库">
                <i class="fa fa-chevron-left"></i> 本地仓库连接git远程仓库
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2017/11/20/springboot对Mongo增删改查的方式/" rel="prev" title="springboot对Mongo增删改查的方式">
                springboot对Mongo增删改查的方式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">135</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">93</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1、简单配置"><span class="nav-number">1.</span> <span class="nav-text">1、简单配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-在springboot的配置文件-如application-properties-中配置mongo的url"><span class="nav-number">1.0.1.</span> <span class="nav-text">1.1 在springboot的配置文件 (如application.properties)中配置mongo的url</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-在需要使用mongo的地方引入MongoTemplate来与数据库交互"><span class="nav-number">1.0.2.</span> <span class="nav-text">1.2 在需要使用mongo的地方引入MongoTemplate来与数据库交互</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2、Mongo的配置"><span class="nav-number">2.</span> <span class="nav-text">2、Mongo的配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-正springboot配置文件中-配置mongo的参数信息"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 正springboot配置文件中 配置mongo的参数信息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-配置MongoTemplate"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.2 配置MongoTemplate</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-使用MongoTemplate"><span class="nav-number">2.0.3.</span> <span class="nav-text">2.3 使用MongoTemplate</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-多数据源配置"><span class="nav-number">3.</span> <span class="nav-text">3 多数据源配置</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
